package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.customer.constants.CommonDBFieldsConstants;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public PageResult<AddressBook> page(AddressBookPageQueryReqDTO dto) {
        // 获取当前用户
        Long userId = UserContext.currentUserId();

        Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(dto, AddressBook.class);

        this.lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .orderByDesc(AddressBook::getCreateTime)
                .page(addressBookPage);

        return PageUtils.toPage(addressBookPage, AddressBook.class);
    }

    @Override
    public void addAddressBook(AddressBookUpsertReqDTO dto) {
        // 获取用户id
        CurrentUserInfo currentUserInfo = UserContext.currentUser();

        String[] LonLan = dto.getLocation().split(",");
        AddressBook addressBook = BeanUtils.toBean(dto, AddressBook.class);
        long snowflakeNextId = IdUtils.getSnowflakeNextId();
        addressBook.setId(snowflakeNextId);
        addressBook.setLon(Double.valueOf(LonLan[0]));
        addressBook.setLat(Double.valueOf(LonLan[1]));
        addressBook.setUserId(currentUserInfo.getId());

        // 已默认的地址簿取消默认
        if(CommonDBFieldsConstants.IS_DEFAULT.equals(dto.getIsDefault())){
            this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_NOT_DEFAULT)
                    .eq(AddressBook::getUserId, currentUserInfo.getId())
                    .eq(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
                    .update();
        }

        baseMapper.insert(addressBook);
    }

    @Override
    public void updateById(Long id, AddressBookUpsertReqDTO dto) {
        // 获取用户id
        Long userId = UserContext.currentUserId();

        AddressBook addressBook = BeanUtils.toBean(dto, AddressBook.class);
        long snowflakeNextId = IdUtils.getSnowflakeNextId();
        addressBook.setId(snowflakeNextId);

        // 如果location不为null
        if(dto.getLocation()!=null){
            String[] LonLan = dto.getLocation().split(",");

            addressBook.setLon(Double.valueOf(LonLan[0]));
            addressBook.setLat(Double.valueOf(LonLan[1]));
        }

        addressBook.setUserId(userId);

        this.lambdaUpdate()
                .eq(AddressBook::getId, id)
                .update(addressBook);
    }

    @Override
    public void batchDelete(String ids) {
        if(!StrUtil.isNotBlank(ids)){
            throw new ForbiddenOperationException("未选中任何删除的值");
        }

        JSONArray objects = JSONUtil.parseArray(ids);

        List<Long> idList = objects.stream().map(o -> Long.valueOf((String) o)).collect(Collectors.toList());

        baseMapper.deleteBatchIds(idList);
    }

    @Override
    public void onOffDefault(Integer flag, Long id) {
        // 判断id所属对象是否存在
        AddressBook addressBook = this.lambdaQuery().eq(AddressBook::getId, id).one();
        if(ObjectUtil.isNull(addressBook)){
            throw new ForbiddenOperationException("不存在该地址簿");
        }

        // 取消已默认的地址簿
        this.lambdaUpdate()
                .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_NOT_DEFAULT)
                .eq(AddressBook::getUserId, addressBook.getUserId())
                .eq(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
                .update();

        if(CommonDBFieldsConstants.IS_DEFAULT.equals(flag)){
            // 设置默认
            this.lambdaUpdate()
                    .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
                    .eq(AddressBook::getId, id)
                    .update();
        }

//        if(CommonDBFieldsConstants.IS_DEFAULT.equals(flag)){
//            // 取消已默认的地址簿
//            this.lambdaUpdate()
//                    .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_NOT_DEFAULT)
//                    .eq(AddressBook::getUserId, addressBook.getUserId())
//                    .eq(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
//                    .update();
//
//            // 设置默认
//            this.lambdaUpdate()
//                    .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
//                    .eq(AddressBook::getId, id)
//                    .update();
//        }else {
//            // 取消默认
//            this.lambdaUpdate()
//                    .set(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_NOT_DEFAULT)
//                    .eq(AddressBook::getUserId, addressBook.getUserId())
//                    .eq(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
//                    .update();
//        }
    }

    @Override
    public AddressBook getDefault() {
        Long userId = UserContext.currentUserId();

        return this.lambdaQuery()
                .eq(AddressBook::getIsDefault, CommonDBFieldsConstants.IS_DEFAULT)
                .eq(AddressBook::getUserId, userId)
                .one();
    }
}
